<?php

namespace app\admin\controller;

use app\common\model\Admin;
use app\common\lib\Token;
use think\facade\Cache;
use think\facade\View;
use think\facade\Session;

// use app\common\model\SystemAdmin;

/**
 * ERROR CODE
 * 1001 管理员账号错误
 * 1002 管理员密码错误
 */
class Login extends AdminController
{
	public function index ()
	{
		// dump($this->request->admin);
		if ($this->request->admin) {
			return redirect('/admin');
		}
		return View::fetch("login/index");
	}

	/* web login auth */
	public function auth ()
	{
		$username = request()->param('username');
		$password = request()->param('password');
		$admin = Admin::where('username', $username)->findOrEmpty();
		if ($admin->isEmpty()) {
			return success(1001, '账号不存在 ~');
		}
		// 校验密码
		if (!password_verify($password, $admin['password'])) {
			return success(1002, '密码不正确 ~');
		} else {
			// 剔除密码敏感字段
			unset($admin['password']);
			// 获取 token
			$token = Token::create();
			// 转化数组 $admin
			$admin = $admin->toArray();
			// 设置 redis 缓存
			Cache::set('sys_admin', $admin, 300);
			// 设置 session
			Session::set("sys_admin", $admin);
			$data['token'] = $token;
			$data['userInfo'] = $admin;
			return success(200, "登录成功~", $data);
		}
	}

}